<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>状态管理Vuex</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/vuex@4/dist/vuex.global.js"></script>
</head>
<body>
    <div id="app">
        <p>普通数据num：{{num}}</p>
        <p>直接获取状态管理中数据state.count：{{$store.state.count}}</p>
        <p>使用计算属性变成响应式数据computedCount：{{computedCount}}</p>
        <p>转为ref对象ref_count：{{ref_count}}</p>
        <!--改变store中state-->
        <button @click="add">增加</button>
    </div>
    <script>
        //1.定义Vuex的store实例
        const store = Vuex.createStore({
            state() {
                return {
                    count: 0
                }
            },
            //唯一更改state数据的方法
            mutations: {
                increment(state) {
                    state.count++
                }
            }
        });

        //2.绑定
        Vue.createApp({
            setup() {
                //定义普通常量
                const num = Vue.ref(123);
                
                //改变store中数据
                function add() {
                    num.value++;
                    //store中数据的改变：提交给store中mutation处理
                    store.commit("increment");
                    //store.state.count++
                }
                
                //使用计算属性变成响应式数据
                const computedCount = Vue.computed(() => store.state.count);
                
                //转为ref对象
                const { count: ref_count } = Vue.toRefs(store.state);
                
                //返回，以便数据被访问
                return { num, add, computedCount, ref_count }
            }
        }).use(store).mount("#app")
    </script>
</body>
</html>
